package com.my.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class ServiceLogAspect {

    private Date startTime; // 方法开始时间

    // 前置通知：记录方法开始时间
    @Before("execution(* service.*.*(..))")
    public void beforeServiceMethod(JoinPoint joinPoint) {
        startTime = new Date();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        System.out.println("执行前: " + new Date());
        System.out.println("执行了[" + className + "." + methodName + "]操作");
        System.out.println("参数: " + Arrays.toString(args));
    }

    // 后置通知：记录方法执行耗时
    @After("execution(* service.*.*(..))")
    public void afterServiceMethod(JoinPoint joinPoint) {
        Date endTime = new Date();
        long duration = endTime.getTime() - startTime.getTime();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();

        System.out.println("执行后: " + endTime);
        System.out.println("[" + className + "." + methodName + "]执行耗时: " + duration + "ms");
        System.out.println("----------------------------------------");
    }
}